package xml;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

//import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
//import org.dom4j.Node;
//import org.dom4j.VisitorSupport;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.dom4j.DocumentException;

public class MyDom4j {
	private static XMLWriter writer = null;

	public static Document Read(String fileName) throws DocumentException,
			Exception {
		SAXReader reader = new SAXReader();
		Document document = reader.read(new File(fileName));
		return document;
	}

	public static Element GetRootElement(Document doc) {
		return doc.getRootElement();
	}

	public static Document CreatDocumentRoot(String rootName) {

		Document document = DocumentHelper.createDocument();
		document.addElement(rootName);
		return document;
	}

	public static void AddRootAttribute(Document doc, String attributeName,
			String attributeVaule) {
		Element root = doc.getRootElement();
		root.addAttribute(attributeName, attributeVaule);
		return;
	}

	public static Element AddElementWithText(Element father, String son,
			String text) {
		Element sonElement = father.addElement(son).addText(text);
		return sonElement;
	}

	public static void CreatXML(Document doc, String path, String fileName)
			throws IOException {
		if (doc != null) {
			OutputFormat format = OutputFormat.createPrettyPrint();
			try {
				writer = new XMLWriter(
						new FileWriter(new File(path, fileName)), format);
				writer.write(doc);
			} catch (Exception ex) {
				ex.printStackTrace();
			} finally {
				writer.close();
			}
		}
	}

	// public static void AddAttribute(Element father,String son,String text)
	// {
	// father.addElement(son).addText(text);
	// }

	public static void main(String args[]) throws DocumentException, Exception {
		String fileName = "C:\\Users\\Administrator\\workspace\\Graduate\\CHANGETEST.xml ";

		Document doc = MyDom4j.Read(fileName);
		Element root = MyDom4j.GetRootElement(doc);

		for (@SuppressWarnings("unchecked")
		Iterator<Element> i = root.elementIterator("TABLE"); i.hasNext();) {
			Element foo = i.next();
			System.out.println(foo.attributeValue("TABLE_NAME"));
		}

		// System.out .println(table);
		// Attribute a = table.attribute("TABLE_1") ;

		// s = root.asXML();
		// System.out .println(s);
		// s = root.getText();
		// System.out.println(s);
	}

}
